<!-- 表字段 -->
<template>
  <div class="table-fields">
    <div class="table-top">
      <div>编辑表字段：</div>
      <el-select
        v-model="primaryKeyField"
        size="small"
        placeholder="请选择主键"
      >
        <el-option
          v-for="item in primaryKeyList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
          @click="changeSelect($event)"
        />
      </el-select>
    </div>
    <el-table
      :data="useFiledList"
      :cell-style="{ color: '#333333' }"
      :header-cell-style="{ background: '#F3F4F7', color: '#000000' }"
    >
      <el-table-column
        prop="columnField"
        label="字段名"
        min-width="150"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <el-input
            v-if="scope.row.isEdit"
            v-model.trim="scope.row.columnField"
            size="small"
            placeholder="请输入字段名"
          ></el-input>
          <template v-else>
            {{ scope.row.columnField }}
          </template>
        </template>
      </el-table-column>
      <el-table-column
        prop="columnType"
        label="字段类型"
        min-width="150"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <el-select
            v-if="scope.row.isEdit"
            v-model="scope.row.columnTypeId"
            size="small"
            placeholder="请选择字段类型"
          >
            <el-option
              v-for="i in useFiledOptions"
              :key="i.value"
              :label="i.label"
              :value="i.value"
            ></el-option>
          </el-select>
          <template v-else>
            {{ scope.row.columnType }}
          </template>
        </template>
      </el-table-column>
      <el-table-column
        prop="columnPrecision"
        label="精度"
        min-width="150"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <el-input
            v-if="scope.row.isEdit"
            v-model.trim="scope.row.columnPrecision"
            size="small"
            placeholder="请输入精度"
          ></el-input>
          <template v-else>
            {{ scope.row.columnPrecision }}
          </template>
        </template>
      </el-table-column>
      <el-table-column
        prop="columnScale"
        label="标度"
        min-width="150"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <el-input
            v-if="scope.row.isEdit"
            v-model.trim="scope.row.columnScale"
            size="small"
            placeholder="请输入标度"
          ></el-input>
          <template v-else>
            {{ scope.row.columnScale }}
          </template>
        </template>
      </el-table-column>
      <el-table-column
        prop="columnRemark"
        label="注释"
        min-width="150"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <el-input
            v-if="scope.row.isEdit"
            v-model.trim="scope.row.columnRemark"
            size="small"
            placeholder="请输入注释"
          ></el-input>
          <template v-else>
            {{ scope.row.columnRemark }}
          </template>
        </template>
      </el-table-column>
      <el-table-column
        prop="isAllowNullStatus"
        label="是否为空"
        min-width="150"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <el-select
            v-if="scope.row.isEdit"
            v-model="scope.row.isAllowNull"
            size="small"
            placeholder="请选择是否为空"
          >
            <el-option
              v-for="i in allowNullOptions"
              :key="i.value"
              :label="i.label"
              :value="i.value"
            ></el-option>
          </el-select>
          <template v-else>
            <template v-if="scope.row.isAllowNull === 0"> 否 </template>
            <template v-else-if="scope.row.isAllowNull === 1"> 是 </template>
            <template v-else> --- </template>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="center" width="250">
        <template slot-scope="scope">
          <template v-if="scope.row.isEdit">
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="saveField(scope.row)"
              >保存</el-link
            >
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="cancelOpera(scope.row, scope.$index)"
              >取消</el-link
            >
          </template>
          <template v-else>
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="editField(scope.row)"
              >编辑</el-link
            >
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="deleteField(scope.row, scope.$index)"
              >删除</el-link
            >
          </template>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align: right; margin: 10px 20px">
      <el-button type="primary" size="small" @click="addField">新增</el-button>
    </div>
  </div>
</template>
<script>
import cloneDeep from "lodash/cloneDeep";
export default {
  name: "FieldsList",
  props: {
    fieldsList: {
      type: Array,
      default: () => [],
    },
    primaryList: {
      type: Array,
      default: () => [],
    },
    primaryKeyId: {
      type: String,
    },
  },
  data() {
    return {
      // 主键信息
      primaryKeyField: null,
      // 主键可选列表
      primaryKeyList: [],
      useFiledList: [],
      allowNullOptions: [
        {
          value: 0,
          label: "否",
        },
        {
          value: 1,
          label: "是",
        },
      ],
      // 存储字段信息set
      fieldNameSet: new Set(),
      // 记录当前编辑字段行
      currentRow: {}
    };
  },
  inject: ["filedOptions"],
  computed: {
    useFiledOptions() {
      return this.filedOptions();
    },
  },
  watch: {
    fieldsList: {
      handler(val, olVal) {
        // 先置空
        this.fieldNameSet = new Set();
        // 再添加
        this.useFiledList = cloneDeep(val);
        for (let i of val) {
          this.fieldNameSet.add(i.columnField);
        }
      },
      immediate: true,
    },
    primaryList: {
      handler(val, olVal) {
        this.primaryKeyList = cloneDeep(val);
      },
      immediate: true,
    },
    primaryKeyId: {
      handler(val, olVal) {
        this.primaryKeyField = val;
      },
      immediate: true,
    },
  },
  methods: {
    changeSelect() {},
    addField() {
      this.useFiledList.push({
        columnField: null,
        columnType: null,
        columnTypeId: null,
        columnPrecision: null,
        columnScale: null,
        columnRemark: null,
        isAllowNullStatus: null,
        isEdit: true,
        isAdd: true,
      });
    },
    editField(row) {
      this.currentRow = cloneDeep(row)
      // 编辑时先移除当前行columnField
      this.fieldNameSet.delete(row.columnField);
      this.$set(row, "isEdit", true);
    },
    deleteField(row, index) {
      let primaryIndex = this.primaryKeyList.findIndex(
        (i) => i.value === row.columnField
      );
      this.primaryKeyList.splice(primaryIndex, 1);
      this.fieldNameSet.delete(row.columnField);
      this.useFiledList.splice(index, 1);
    },
    saveField(row) {
      if (!this.checkFields(row)) {
        return;
      }
      let item = this.useFiledOptions.find((i) => i.value === row.columnTypeId);
      this.$set(row, "columnType", item ? item.label : "");
      // 如果是新增行 保存时将新增标识设置为false
      if(row.isAdd) {
        row.isAdd = false
        this.fieldNameSet.add(row.columnField);
        this.primaryKeyList.push({
          label: row.columnField,
          value: row.columnField,
        });
      } else {
        // 编辑时修改
        if (this.currentRow.columnField !== row.columnField) {
          // 移除旧的字段信息
          let primaryIndex = this.primaryKeyList.findIndex(
          (i) => i.label === this.currentRow.columnField
          );
          if (primaryIndex !== -1) {
            this.primaryKeyList.splice(primaryIndex, 1);
            // 增加新的字段信息
            this.primaryKeyList.splice(primaryIndex, 0, {
              label: row.columnField,
              value: row.columnField,
            });
          }
        }
        // 无论字段是否变化 都需要添加columnField到set（点击编辑时移除了）
        this.fieldNameSet.add(row.columnField)
      }

      this.$set(row, "isEdit", false);
    },
    checkFields(row, showTips = true, ignoreRepeat = false) {
      if (row.columnField === "" || row.columnField === null) {
        this.$message.warning("字段名不能为空!");
        return false;
      }
      // if (!ignoreRepeat) {
      if (this.fieldNameSet.has(row.columnField)) {
        this.$message.warning("字段名禁止重复!");
        return false;
      }
      // }

      if (row.columnTypeId === null) {
        this.$message.warning("字段类型不能为空!");
        return false;
      }
      if (row.columnPrecision === "" || row.columnPrecision === null) {
        this.$message.warning("字段精度不能为空!");
        return false;
      }
      return true;
    },
    cancelOpera(row, index) {
      if (row.id || !row.isAdd) {
        // this.$set(row, "isEdit", false);
        // 复原信息
        for (let k in row) {
          row[k] = this.currentRow[k]
        }
        this.fieldNameSet.add(this.currentRow.columnField);
      } else {
        this.useFiledList.splice(index, 1);
      }
    },
    // checkList() {
    //   let flag = true;
    //   let index = 0;
    //   for (let i = 0; i < this.useFiledList.length; i++) {
    //     if (!this.checkFields(this.useFiledList[i], false, true)) {
    //       flag = false;
    //       index = i;
    //       console.log(this.useFiledList[i]);
    //       break;
    //     }
    //   }
    //   if (!flag) {
    //     this.$message.warning(
    //       `表字段第${index + 1}条数据信息校验未通过，请修改并保存或删除该数据`
    //     );
    //   }
    //   return flag;
    // },
  },
};
</script>
<style lang="scss" scoped>
.table-top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.ontology-edit {
  padding: 0 10px;

  & + .ontology-edit {
    border-left: 1px solid #dddddd;
  }
}
</style>
